const tokenHelper = appRequire('common/tokenHelper');
const thisRequest = require('sync-request');
const {
	Op
} = require('sequelize');

// 引入模型
const baiduCourseModel = appRequire('models/baiduCourse');

// 导出对象，供其它模块调用
module.exports = {
	getBaiduCourseList,
	getSyncedCourseList,
	syncCourses,
	updateCourse,
	deleteCourse
};

/**
 * 提取课程名称中的序号
 * @param {string} name 课程名称
 * @returns {object} { order: 序号, displayName: 去掉数字后的显示名称 }
 */
function extractOrder(name) {
	if (!name) return {
		order: 0,
		displayName: name
	};

	// 匹配开头的数字和可能的分隔符：832《思维创想课》、99、最美中国字、123.课程名 等
	const match = name.match(/^(\d+)[、\.．\s]*(.*)/);
	if (match) {
		const order = parseInt(match[1]);
		const displayName = match[2].trim();
		return {
			order,
			displayName: displayName || name // 如果没有剩余内容，使用原名称
		};
	}

	return {
		order: 0,
		displayName: name
	};
}

/**
 * 获取百度网盘课程列表
 * 从百度API获取指定目录的文件夹列表
 */
async function getBaiduCourseList(req, request) {
	let postData = req.body;
	let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

	try {
		// 从数据库获取百度网盘token
		const access_token = await tokenHelper.getBaiduToken();

		// 支持传入path参数浏览不同层级,默认为/apps/course
		const basePath = postData.path || '/apps/course';

		// 分页参数
		const pageNum = postData.pageNum || 1;
		const pageSize = postData.pageSize || 200;
		const start = (pageNum - 1) * pageSize;

		// 调用百度网盘API获取文件列表（支持分页）
		const baiduApi = "http://pan.baidu.com/rest/2.0/xpan/file";
		const url =
			`${baiduApi}?method=list&access_token=${access_token}&dir=${encodeURIComponent(basePath)}&order=name&desc=0&start=${start}&limit=${pageSize}`;

		console.log('📁 正在获取百度网盘课程列表:', basePath, `第${pageNum}页，每页${pageSize}条`);

		var res = thisRequest('GET', url, {
			headers: {
				'User-Agent': 'pan.baidu.com'
			}
		});

		var body = res.getBody();
		var jsonObj = JSON.parse(body);

		if (jsonObj.errno !== 0) {
			console.error('❌ 百度网盘API返回错误:', jsonObj);
			returnData.msg = jsonObj.errmsg || '获取课程列表失败';
			returnData.code = -1;
			return request.json(returnData);
		}

		// 过滤出文件夹（课程）
		const folders = jsonObj.list ? jsonObj.list.filter(item => item.isdir === 1) : [];

		console.log(`✅ 成功获取 ${folders.length} 个课程文件夹`);

		// 查询数据库中已同步的课程（基于fs_id）
		const syncedFsIds = await baiduCourseModel.findAll({
			attributes: ['fs_id'],
			raw: true
		});
		const syncedSet = new Set(syncedFsIds.map(item => item.fs_id));

		// 映射为课程数据结构，并标记同步状态
		const courses = folders.map(folder => {
			const {
				order,
				displayName
			} = extractOrder(folder.server_filename);
			const isSynced = syncedSet.has(folder.fs_id.toString());

			return {
				fs_id: folder.fs_id.toString(),
				name: folder.server_filename,
				displayName: displayName,
				order: order,
				path: folder.path,
				createTime: formatTimestamp(folder.server_ctime),
				updateTime: formatTimestamp(folder.server_mtime),
				isSynced: isSynced,
				folderInfo: JSON.stringify({
					fs_id: folder.fs_id,
					path: folder.path,
					server_filename: folder.server_filename,
					server_ctime: folder.server_ctime,
					server_mtime: folder.server_mtime,
					isdir: folder.isdir
				})
			};
		});

		returnData.code = 1;
		returnData.data = {
			total: courses.length, // 当前页的数量
			list: courses,
			basePath: basePath,
			pageNum: pageNum,
			pageSize: pageSize,
			hasMore: courses.length >= pageSize // 如果返回数量等于pageSize，可能还有更多数据
		};

		request.json(returnData);

	} catch (error) {
		console.error('❌ 获取百度网盘课程列表失败:', error);
		returnData.msg = error.message || '获取课程列表失败';
		returnData.code = -1;
		request.json(returnData);
	}
}

/**
 * 查询已同步的课程列表
 * 从数据库查询
 */
async function getSyncedCourseList(req, request) {
	let postData = req.body;
	let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

	try {
		const pageNum = postData.pageNum || 1;
		const pageSize = postData.pageSize || 20;
		const keyword = postData.keyword || '';

		// 构建查询条件
		const where = {};
		if (keyword) {
			where[Op.or] = [{
					name: {
						[Op.like]: `%${keyword}%`
					}
				},
				{
					displayName: {
						[Op.like]: `%${keyword}%`
					}
				}
			];
		}

		// 查询数据库
		const result = await baiduCourseModel.findAndCountAll({
			where,
			order: [
				['order', 'ASC'],
				['name', 'ASC']
			],
			offset: (pageNum - 1) * pageSize,
			limit: pageSize
		});

		console.log(`✅ 查询到 ${result.count} 个已同步课程`);

		returnData.code = 1;
		returnData.data = {
			total: result.count,
			list: result.rows,
			pageNum: pageNum,
			pageSize: pageSize
		};

		request.json(returnData);

	} catch (error) {
		console.error('❌ 查询已同步课程列表失败:', error);
		returnData.msg = error.message || '查询失败';
		returnData.code = -1;
		request.json(returnData);
	}
}

/**
 * 批量同步课程到数据库
 */
async function syncCourses(req, request) {
	let postData = req.body;
	let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

	try {
		const courses = postData.courses || []; // 课程列表数组

		if (!courses || courses.length === 0) {
			returnData.msg = '请选择要同步的课程';
			returnData.code = -1;
			return request.json(returnData);
		}

		let successCount = 0;
		let duplicateCount = 0;
		let failedCount = 0;
		const errors = [];

		// 逐个同步课程
		for (const course of courses) {
			try {
				// 检查是否已存在（基于fs_id）
				const existing = await baiduCourseModel.findOne({
					where: {
						fs_id: course.fs_id
					}
				});

				if (existing) {
					duplicateCount++;
					console.log(`⚠️ 课程已存在，跳过: ${course.name}`);
					continue;
				}

				// 生成百度网盘分享链接
				console.log(`🔗 正在生成分享链接: ${course.name}...`);
				const baiduDeskLink = await generateShareLink(course.fs_id);

				if (baiduDeskLink) {
					console.log(`✅ 分享链接生成成功`);
				} else {
					console.log(`⚠️  分享链接生成失败，将继续同步课程`);
				}

				// 创建新记录
				const objectId = sid.uuid();
				await baiduCourseModel.create({
					objectId: objectId,
					name: course.name,
					displayName: course.displayName,
					order: course.order || 0,
					path: course.path,
					fs_id: course.fs_id,
					createTime: course.createTime || new Date(),
					updateTime: course.updateTime || new Date(),
					syncTime: new Date(),
					folderInfo: course.folderInfo,
					isVisible: true,
					remark: '',
					baiduDeskLink: baiduDeskLink // 存储分享链接
				});

				successCount++;
				console.log(`✅ 同步成功: ${course.name}`);

			} catch (error) {
				failedCount++;
				errors.push({
					name: course.name,
					error: error.message
				});
				console.error(`❌ 同步失败: ${course.name}`, error);
			}
		}

		returnData.code = 1;
		returnData.data = {
			success: successCount,
			duplicate: duplicateCount,
			failed: failedCount,
			total: courses.length,
			errors: errors
		};

		returnData.msg = `同步完成！成功${successCount}个，重复${duplicateCount}个，失败${failedCount}个`;

		request.json(returnData);

	} catch (error) {
		console.error('❌ 批量同步课程失败:', error);
		returnData.msg = error.message || '同步失败';
		returnData.code = -1;
		request.json(returnData);
	}
}

/**
 * 更新课程信息
 */
async function updateCourse(req, request) {
	let postData = req.body;
	let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

	// 检查必填参数
	let checkResult = Common.checkUrl(postData, ['objectId'], request);
	if (checkResult == false) return;

	try {
		const objectId = postData.objectId;
		const updateData = {};

		// 允许更新的字段
		if (postData.name !== undefined) updateData.name = postData.name;
		if (postData.displayName !== undefined) updateData.displayName = postData.displayName;
		if (postData.order !== undefined) updateData.order = postData.order;
		if (postData.isVisible !== undefined) updateData.isVisible = postData.isVisible;
		if (postData.remark !== undefined) updateData.remark = postData.remark;

		// 更新数据库
		const result = await baiduCourseModel.update(updateData, {
			where: {
				objectId: objectId
			}
		});

		if (result[0] === 0) {
			returnData.msg = '课程不存在';
			returnData.code = -1;
			return request.json(returnData);
		}

		console.log(`✅ 更新课程成功: ${objectId}`);
		returnData.code = 1;
		returnData.msg = '更新成功';

		request.json(returnData);

	} catch (error) {
		console.error('❌ 更新课程失败:', error);
		returnData.msg = error.message || '更新失败';
		returnData.code = -1;
		request.json(returnData);
	}
}

/**
 * 删除课程
 */
async function deleteCourse(req, request) {
	let postData = req.body;
	let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

	// 检查必填参数
	let checkResult = Common.checkUrl(postData, ['objectId'], request);
	if (checkResult == false) return;

	try {
		const objectId = postData.objectId;

		// 物理删除
		const result = await baiduCourseModel.destroy({
			where: {
				objectId: objectId
			}
		});

		if (result === 0) {
			returnData.msg = '课程不存在';
			returnData.code = -1;
			return request.json(returnData);
		}

		console.log(`✅ 删除课程成功: ${objectId}`);
		returnData.code = 1;
		returnData.msg = '删除成功';

		request.json(returnData);

	} catch (error) {
		console.error('❌ 删除课程失败:', error);
		returnData.msg = error.message || '删除失败';
		returnData.code = -1;
		request.json(returnData);
	}
}

/**
 * 生成百度网盘分享链接
 * @param {string} fs_id 文件ID
 * @returns {Promise<string>} 分享链接，失败返回null
 */
async function generateShareLink(fs_id) {
	try {
		// 获取配置
		const bdstoken = await tokenHelper.getBaiduBdstoken();
		const logid = await tokenHelper.getBaiduLogid();
		const cookie = await tokenHelper.getBaiduCookie();

		// 调用百度API创建分享链接（参数在URL中）
		const url = `https://pan.baidu.com/share/set?channel=chunlei&bdstoken=${bdstoken}&clienttype=0&app_id=250528&web=1&dp-logid=${logid}&fid_list=[${fs_id}]&schannel=4&pwd=1090&period=0`;

		console.log('🔍 请求URL:', url);

		// 使用 thisRequest 发送请求，body 为空 json
		const res = thisRequest('POST', url, {
			json: {},
			headers: {
				'User-Agent': 'pan.baidu.com',
				'Content-Type': 'application/x-www-form-urlencoded',
				'Cookie': cookie
			}
		});

		const body = res.getBody();
		const jsonObj = JSON.parse(body);

		console.log('📦 百度API返回:', jsonObj);

		if (jsonObj.errno === 0 && jsonObj.link) {
			console.log(`✅ 生成分享链接成功: ${jsonObj.link}`);
			return jsonObj.link;
		} else {
			console.error(`⚠️  生成分享链接失败: errno=${jsonObj.errno}`, jsonObj);
			return null;
		}

	} catch (error) {
		console.error('❌ 生成分享链接异常:', error.message);
		return null;
	}
}

/**
 * 格式化时间戳
 * @param {number} timestamp 时间戳（秒）
 * @returns {string} 格式化的时间字符串
 */
function formatTimestamp(timestamp) {
	if (!timestamp) return '';

	const date = new Date(timestamp * 1000); // 转换为毫秒
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hour = String(date.getHours()).padStart(2, '0');
	const minute = String(date.getMinutes()).padStart(2, '0');
	const second = String(date.getSeconds()).padStart(2, '0');

	return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
